<template>
  <div class="flex justify-between items-center w-full">
    <el-input
      style="width: 65%"
      v-model="validCode"
      :placeholder="placeholder"
      show-word-limit
      clearable
      autocomplete="off"
    />
    <el-button
      v-if="time !== 60"
      class="flex-1 h-[40px] cursor-pointer"
      type="info"
      disabled
    >
      {{ $t("register.validCodeTime", { time }) }}
    </el-button>
    <el-button
      v-else
      class="flex-1 h-[40px] cursor-pointer ml-2"
      type="primary"
      @click="getValidCode"
    >
      {{ $t("register.getValidCode") }}
    </el-button>
  </div>
</template>
<script lang="ts" setup>
import { ref, type PropType } from "vue";
import { sendcode } from "@/api/auth";
import type { SendValidCodeReq } from "@/api/auth/types";
import { vueMetaEnv } from "@/settings";
import { useUserStore } from "@/stores";
import type { FormInstance } from "element-plus";

const validCode = defineModel<string>();

const props = defineProps({
  name: {
    type: String,
    default: "",
  },
  captchaId: {
    type: String,
    default: "",
  },
  captchaCode: {
    type: String,
    default: "",
  },
  formRef: {
    type: Object as PropType<FormInstance>,
    default: null,
  },
  placeholder: {
    type: String,
    default: "",
  },
  validateField: {
    type: Array as PropType<string[]>,
    default: [],
  },
});

const time = ref(60);
const interval = ref<number | null>(null);
const getValidCode = () => {
  if (time.value !== 60) return;
  props.formRef?.validateField(props.validateField, async (valid) => {
    if (!valid) return;
    const codeForm: SendValidCodeReq = {
      name: props.name,
      captchaId: props.captchaId,
      captchaCode: props.captchaCode,
      tenant: useUserStore().user.tenant,
      sendValidCode: true,
      directoryId: vueMetaEnv.APP_DIRECTORY_ID as string,
      product: vueMetaEnv.APP_PRODUCT as string,
    };
    await sendcode(codeForm);
    ElMessage.success("验证码发送成功，请注意查收！");
    interval.value = setInterval(() => {
      if (time.value <= 0 && interval.value) {
        clearInterval(interval.value);
        time.value = 60;
        return;
      }
      time.value--;
    }, 1000);
  });
};
</script>
